package com.itheima.service.impl;

import com.itheima.mapper.*;
import com.itheima.pojo.CheckGroup;
import com.itheima.pojo.CheckItem;
import com.itheima.pojo.Setmeal;
import com.itheima.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class SetmealServiceImplDiscard implements SetmealService {
    @Autowired
    private SetmealMapper setmealMapper;
    @Autowired
    private SetmealCheckGroupMapper setmealCheckGroupMapper;
    @Autowired
    private CheckGroupMapper checkGroupMapper;
    @Autowired
    private CheckGroupCheckItemMapper checkGroupCheckItemMapper;
    @Autowired
    private CheckItemMapper checkItemMapper;


    /**
     * 查询所有套餐
     * @return
     */
    @Override
    public List<Setmeal> findAll() {
        return setmealMapper.selectAll();
    }

    /**
     * 根据套餐id查询套餐详情
     * @param id
     * @return
     */
    @Override
    public Setmeal findById(Integer id) {
        // 首先查询套餐基本信息
        Setmeal setmeal = setmealMapper.findById(id);
        if(setmeal == null) return setmeal;

        // 根据套餐id查询套餐关联的检查组
        List<Integer> checkGroupIds = setmealCheckGroupMapper.selectBySetmealId(id);
        if(checkGroupIds == null || checkGroupIds.isEmpty()) return setmeal;
        log.info("根据套餐id查询套餐关联的检查组, ids为{}", checkGroupIds);

        // 根据检查组id查询检查组
        setmeal.setCheckGroups(new ArrayList<>());
        for (Integer checkGroupId : checkGroupIds) {
            // 得到每一个检查组
            CheckGroup group = checkGroupMapper.selectById(checkGroupId);
            log.info("查询检查组{}, {}", checkGroupId, group);

            // 如果检查组是空的直接跳过
            // TODO理论上不存在关联的不存在这种情况，应该抛出异常
            if(group == null) continue;

            // 根据检查组id查询检查组关联的检查项
            List<Integer> checkItemIds = checkGroupCheckItemMapper.findItemIdsByCheckGroupId(checkGroupId);
            log.info("根据检查组id查询检查组关联的检查项, ids为{}", checkItemIds);
            // 不能为空
            if(checkItemIds != null && !checkItemIds.isEmpty()){
                group.setCheckItems(new ArrayList<>());
                for (Integer checkItemId : checkItemIds) {
                    CheckItem checkItem = checkItemMapper.findById(checkItemId);
                    log.info("查询检查项{}, {}", checkItemId, checkItem);
                    group.getCheckItems().add(checkItem);
                }
            }
            setmeal.getCheckGroups().add(group);
        }
        return setmeal;

    }
}
